//
//  TextFieldWithLRView.swift
//  SitPosition
//
//  Created by apple on 2018/12/31.
//  Copyright © 2018 apple. All rights reserved.
//

import Foundation
import UIKit


/**
 * 根据UITextField的leftView和rightView调整输入光标的位置
 * 防止光标紧挨着leftView、rightView，显示效果会比较差。
 */
class TextFieldWithLRView : UITextField {
    
    var leftViewInsets: UIEdgeInsets = UIEdgeInsets.zero {
        didSet {
            setNeedsLayout()
        }
    }
    var rightViewInsets: UIEdgeInsets = UIEdgeInsets.zero {
        didSet {
            setNeedsLayout()
        }
    }
    
    override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
        var rect = super.leftViewRect(forBounds: bounds)
        guard leftView != nil else { return rect }
        
        rect.origin = CGPoint(x: rect.origin.x+leftViewInsets.left,
                              y: rect.origin.y+leftViewInsets.top)
        rect.size = CGSize(width: rect.width-(leftViewInsets.left + leftViewInsets.right),
                           height: rect.height-(leftViewInsets.top + leftViewInsets.bottom))
        return rect
    }
    
    override func rightViewRect(forBounds bounds: CGRect) -> CGRect {
        var rect = super.rightViewRect(forBounds: bounds)
        guard rightView != nil else { return rect }
        
        rect.origin = CGPoint(x: rect.origin.x+rightViewInsets.left,
                              y: rect.origin.y+rightViewInsets.top)
        rect.size = CGSize(width: rect.width-(rightViewInsets.left + rightViewInsets.right),
                           height: rect.height-(rightViewInsets.top + rightViewInsets.bottom))
        return rect
    }
    
    func _textRect(forBounds bounds: CGRect) -> CGRect {
        let kMargin: CGFloat = 13
        var rect = bounds
        if leftView != nil {
            rect.origin.x += kMargin
            rect.size.width -= kMargin
        }
        if rightView != nil {
            rect.size.width -= kMargin
        }
        return rect
    }
    
    override func textRect(forBounds bounds: CGRect) -> CGRect {
        let rect = super.textRect(forBounds: bounds)
        return _textRect(forBounds:rect)
    }
    
    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        let rect = super.textRect(forBounds: bounds)
        return _textRect(forBounds:rect)
    }
}

/**
 * 扩充String，支持RangeExpression协议
 */
extension String {
    func toRange(_ range: NSRange) -> Range<String.Index>? {
        guard let from16 = utf16.index(utf16.startIndex, offsetBy: range.location, limitedBy: utf16.endIndex) else { return nil }
        guard let to16 = utf16.index(from16, offsetBy: range.length, limitedBy: utf16.endIndex) else { return nil }
        guard let from = String.Index(from16, within: self) else { return nil }
        guard let to = String.Index(to16, within: self) else { return nil }
        return from ..< to
    }
}

